<script>
  import * as echarts from "echarts";
  import { onMount, onDestroy } from "svelte";
  import { useChartData } from "../utils/useChartData.js";

  export let endpoint = "";
  export let title = "";
  export let authToken = "";
  export let polling = 0;
  export let data = null;

  let container;
  let chart;

  // Use shared data fetching logic
  const { loading, error, fetchData, cleanup } = useChartData();

  function renderChart(payload) {
    if (!chart) return;

    const seriesData = payload.data ?? payload.series?.[0]?.data ?? [];

    const option = {
      title: {
        text: payload.title ?? title,
        left: "center"
      },
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c} ({d}%)"
      },
      legend: {
        orient: "vertical",
        left: "left",
        data: seriesData.map((item) => item.name)
      },
      series: [
        {
          name: payload.series?.[0]?.name ?? title,
          type: "pie",
          radius: payload.radius ?? ["35%", "70%"],
          center: ["50%", "55%"],
          avoidLabelOverlap: false,
          data: seriesData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)"
            }
          }
        }
      ]
    };

    chart.setOption(option, true);
  }

  onMount(() => {
    chart = echarts.init(container);

    // Render provided data immediately
    if (data) {
      renderChart(data);
      loading.set(false);
    }
    // Otherwise fetch from endpoint
    else if (endpoint) {
      fetchData(endpoint, authToken, polling, renderChart);
    }
  });

  onDestroy(() => {
    cleanup();
    chart?.dispose();
  });
</script>

<div class="chart" bind:this={container}></div>
{#if $loading}
  <p class="status">Loading data...</p>
{:else if $error}
  <p class="status error">{$error}</p>
{/if}

<style>
  .chart {
    width: 100%;
    min-height: 280px;
  }
  .status {
    margin-top: 0.5rem;
    font-size: 0.875rem;
    color: var(--muted-color, #555);
  }
  .status.error {
    color: #c0392b;
  }
</style>

